package com.nineclock.document.service.impl;

import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.CountUtil;
import com.nineclock.document.dto.DocFileDto;
import com.nineclock.document.dto.DocFolderDto;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.mapper.DocumentMapper;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @program: nineclock-group-02
 * @description: ${description}
 * @author: TimLi
 * @create: 2021-07-22 11:12
 **/
@Slf4j
@Service
public class DocumentServiceImpl implements DocumentService {

    //注入mapper
    @Autowired
    DocumentMapper documentMapper;

    @Autowired
    DocFolderMapper docFolderMapper;


    /**
     * 新建文档
     * @param docFileDto
     * @return
     */
    @Override
    public void createDoc(DocFileDto docFileDto) {

        //健壮性判断
        if (docFileDto==null || docFileDto.getName().length()==0){
            throw new NcException(ResponseEnum.ERROR);
        }

        // 设置前端传递过来的参数
        DocFile docFile = new DocFile();
        //内容
        docFile.setContent(docFileDto.getContent());
        //名字
        docFile.setName(docFileDto.getName());
        //设置创建用户id
        docFile.setCreateUserId(CurrentUserHolder.get().getCompanyUserId());
        //设置企业id
        docFile.setCompanyId(CurrentUserHolder.get().getCompanyId());
        //创建时间 表中有默认值
        docFile.setCreateTime(new Date());
        //文件路径
        docFile.setFilePath(docFileDto.getFilePath());
        //文件夹id
        docFile.setFolderId(docFileDto.getFolderId());
        //更新用户id
        docFile.setUpdateUserId(CurrentUserHolder.get().getCompanyUserId());
        //设置文件大小
        byte[] bytes = docFileDto.getContent().getBytes();
        //计算输入文本的大小
        String size = CountUtil.getSize(bytes.length);
        docFile.setFileSize(size);

        documentMapper.insert(docFile);

    }

    @Override
    public void createFolder(DocFolderDto docFolderDto) {

        //健壮性判断
        if (docFolderDto == null || docFolderDto.getName().length()<=0){
            throw new NcException(ResponseEnum.ERROR);
        }
        DocFolder docFolder = new DocFolder();

        docFolder.setCompanyId(CurrentUserHolder.get().getCompanyId());
        docFolder.setCreateTime(new Date());
        docFolder.setCreateUserId(CurrentUserHolder.get().getCompanyUserId());
        docFolder.setName(docFolderDto.getName());
        docFolder.setParentId(docFolderDto.getParentId());

        docFolderMapper.insert(docFolder);

    }
}
